package com.shuo;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.ui.JBColor;

import java.awt.*;

public class SimpleDict extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        Editor editor = anActionEvent.getData(PlatformDataKeys.EDITOR);
        if (editor == null) return;
        String sText = editor.getSelectionModel().getSelectedText();
        String translated = getTranslation(sText);
        showTip(translated, editor);
    }

    private void showTip(String msg, Editor editor) {
        ApplicationManager.getApplication().invokeLater(() -> JBPopupFactory.getInstance()
                .createHtmlTextBalloonBuilder(msg, Messages.getInformationIcon(),
                        new JBColor(new Color(214, 241, 255), new Color(0, 200, 250)), null)
                .setFadeoutTime(20000)
                .setHideOnAction(true)
                .createBalloon()
                .show(JBPopupFactory.getInstance().guessBestPopupLocation(editor), Balloon.Position.below));
    }

    private String getTranslation(String word) {
        String result;
        try {
            result = YouDaoUtil.querySimple(word);
        } catch (Exception e) {
            result = null;
        }
        if (result == null || "".equals(result.trim()))
            result = "无结果...";
        return result;
    }

}
